﻿using System;
using System.Diagnostics;

namespace Web7.Dispose
{
    /// <summary>
    /// 启动定时器，并调用销毁后的回调。提供的定时操作封装成了简单的方法 <code>using</code> (C#) 语句.
    /// </summary>
    /// <example>
    /// <code>
    /// Console.WriteLine("Testing Stopwatchdisposable, should be 567:");
    //  using (var timer = new DisposableTimer(result => Console.WriteLine("Took {0}ms", result)))
    //  {
    //      Thread.Sleep(567);
    //  }
    /// </code>
    /// </example>
    public class DisposableTimer : DisposableObject
    {
        private readonly Stopwatch _stopwatch = Stopwatch.StartNew();
        private readonly Action<long> _callback;

        protected DisposableTimer(Action<long> callback)
        {
            _callback = callback;
        }

        public Stopwatch Stopwatch
        {
            get { return _stopwatch; }
        }

        /// <summary>
        /// 启动定时器和销毁时调用指定的回调。
        /// </summary>
        /// <param name="callback">回调.</param>
        /// <returns></returns>
        public static DisposableTimer Start(Action<long> callback)
        {
            return new DisposableTimer(callback);
        }

        public static DisposableTimer TraceDuration<T>(string startMessage, string completeMessage)
        {
            return TraceDuration(typeof(T), startMessage, completeMessage);
        }

        /// <summary>
        /// 追踪时间
        /// </summary>
        /// <param name="loggerType"></param>
        /// <param name="startMessage"></param>
        /// <param name="completeMessage"></param>
        /// <returns></returns>
        public static DisposableTimer TraceDuration(Type loggerType, string startMessage, string completeMessage)
        {
            //LogHelper.TraceIfEnabled(loggerType, () => startMessage);
            //return new DisposableTimer(x => LogHelper.TraceIfEnabled(loggerType, () => completeMessage + " (took " + x + "ms)"));
            return new DisposableTimer(x=> { });
        }

        /// <summary>
        /// 处理处置资源。从抽象类派生过来的 <see cref="DisposableObject"/>锁定逻辑。
        /// </summary>
        protected override void DisposeResources()
        {
            _callback.Invoke(Stopwatch.ElapsedMilliseconds);
        }
    }
}
